package com.aidex.system.service.impl;

import com.aidex.common.core.service.impl.BasicServiceImpl;
import com.aidex.common.exception.BizException;
import com.aidex.common.utils.NumberUtils;
import com.aidex.framework.cache.DictUtils;
import com.aidex.system.common.SysErrorCode;
import com.aidex.system.domain.SysDictData;
import com.aidex.system.mapper.SysDictDataMapper;
import com.aidex.system.service.SysDictDataService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Collection;

@Service
@Transactional(readOnly = true)
public class SysDictDataServiceImpl extends BasicServiceImpl<SysDictDataMapper, SysDictData> implements SysDictDataService {

    @Override
    public int deleteById(Serializable id) {
        SysDictData entity = selectById(id);
        if(entity != null) {
            int flag = super.deleteById(id);
            if (flag > 0) {
                DictUtils.clearDictCache(entity.getDictType());
            }
            return flag;
        }
        return 0;
    }

    @Override
    public int deleteBatchIds(Collection<? extends Serializable> idList) {
        int flag = 0;
        if (idList != null && !idList.isEmpty()) {
            for (Serializable id : idList) {
                flag += deleteById(id);
            }
        }
        return flag;
    }

    @Override
    public int insert(SysDictData entity) {
        int flag = super.insert(entity);
        if (flag > 0) {
            DictUtils.setDictCache(entity.getDictType());
        }
        return flag;
    }

    @Override
    public int updateById(SysDictData entity) {
        int flag = super.updateById(entity);
        if (flag > 0) {
            DictUtils.setDictCache(entity.getDictType());
        }
        return flag;
    }

    @Override
    public void checkDictDataValueUnique(SysDictData dictData) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("dict_type", dictData.getDictType());
        wrapper.eq("dict_value", dictData.getDictValue());
        wrapper.ne("id", dictData.getId());
        if (mapper.selectCount(wrapper) > 0) {
            throw new BizException(SysErrorCode.B_SYSDICDATA_DictValueAlreadyExist);
        }
    }

    @Override
    public int findMaxSort(String dictType) {
        return NumberUtils.nextOrder(mapper.findMaxSort(dictType));
    }
}
